//
//  WSCoinRecordsRequest.m
//  BaseProject
//
//  Created by karong on 2023/8/7.
//

#import "WSCoinRecordsRequest.h"
#import "WSRecord.h"

@implementation WSCoinRecordsRequest
+ (void)loadCoinRecordsListWithYear:(NSInteger)year month:(NSInteger)month page:(NSInteger)page url:(NSString *)url success:(charonTV_ArrayBlock)success failed:(Failure)failed {
    NSDictionary * parameters = @{@"month":WSSF(@"%02ld-%02ld", (long)year, (long)month),
                                  @"page":@(page),
    };
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        NSArray * array = [WSRecord mj_objectArrayWithKeyValuesArray:responseDict[@"items"]];
        success(array);
    } failure:failed];
}

#pragma mark - PagableRequestPotocol
- (void)refreshDataSuccess:(charonTV_ArrayBlock)success failed:(Failure)failed {
    if (self.loading) {
        return;
    }
    self.loading = YES;
    self.haveMore = YES;
    self.page = 1;
    [WSCoinRecordsRequest loadCoinRecordsListWithYear:self.year month:self.month page:self.page url:self.url success:^(NSArray *array) {
        [self loadSuccess:success withArray:array];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        failed(response, error, responseObject);
        self.loading = NO;
    }];
}


- (void)loadMoreDataSuccess:(charonTV_ArrayBlock)success failed:(Failure)failed {
    if (self.loading && !self.haveMore) {
        return;
    }
    [WSCoinRecordsRequest loadCoinRecordsListWithYear:self.year month:self.month page:self.page url:self.url success:^(NSArray *array) {
        [self loadSuccess:success withArray:array];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        failed(response, error, responseObject);
        self.loading = NO;
    }];
}

- (void)loadSuccess:(charonTV_ArrayBlock)success withArray:(NSArray *)array {
    self.haveMore = array.count == 10;
    self.page++;
    self.loading = NO;
    success(array);
}

@end
